package hht.dragon.blog.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import hht.dragon.blog.mapper.ArticleMapper;
import hht.dragon.blog.model.Article;
import hht.dragon.blog.model.Type;
import hht.dragon.blog.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 文章服务实现类.
 * User: huang
 * Date: 18-6-23
 */
@Service
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    private ArticleMapper articleMapper;

    /** 首页最新文章数量. */
    private static final int INDEX_HOT_SIZE = 6;
    /** 分页的每页数量. */
    private static final int PAGE_SIZE = 10;

    @Override
    public boolean save(Article article) {
        boolean ok = false;
        int n = articleMapper.save(article);
        int articleId = article.getArticleId();
        if (n > 0) {
            for (Type type : article.getTypes()) {
                articleMapper.saveTypeArticle(type.getTypeId(), articleId);
            }
            ok = true;
        }
        return ok;
    }

    @Override
    public boolean update(Article article) {
        boolean ok = false;
        int n = articleMapper.updateArticle(article);
        if (n > 0) {
            ok = true;
        }
        return ok;
    }

    @Override
    public boolean delete(int articleId) {
        boolean ok = false;
        int n = articleMapper.deleteArticle(articleId);
        if (n > 0) {
            ok = true;
        }
        return ok;
    }

    @Override
    public List<Article> hotArticle() {
        return articleMapper.getHotArticle(INDEX_HOT_SIZE);
    }

    @Override
    public PageInfo<Article> pageAllArticles(int pageNum, int typeId) {
        PageHelper.startPage(pageNum, PAGE_SIZE);
        List<Article> articles = null;
        if (typeId == 0) {
            articles = articleMapper.getAllArticle();
        } else {
            articles = articleMapper.getAllTypeArticle(typeId);
        }
        PageInfo<Article> pageInfo = new PageInfo<>(articles);
        return pageInfo;
    }

    @Override
    public Article getArticleById(int articleId) {
        return articleMapper.getArticleById(articleId);
    }

    @Override
    public boolean upLike(int articleId) {
        boolean ok = false;
        int n = articleMapper.upLike(articleId);
        if (n > 0) {
            ok = true;
        }
        return ok;
    }

    @Override
    public PageInfo<Article> pageSearchArticle(String search, int pageNum) {
        search = "%" + search + "%";
        PageHelper.startPage(pageNum, PAGE_SIZE);
        List<Article> articles = null;
        articles = articleMapper.searchArticle(search);
        PageInfo<Article> info = new PageInfo<>(articles);
        return info;
    }
}
